#include "tcp_server_fun.h"
#include "common_util.h"

WiFiServer server;
//定义最多多少个client可以连接本server(一般不要超过4个)
WiFiClient serverClients[MAX_TCP_CLIENTS];

void TCPServerInit() {
  Serial.print("init tcp server,prot:");
  Serial.println(TCPProt);
  xTaskCreate(taskServerTCP, "taskServerTCP", 1024 * 10, NULL, 1, NULL);
}

void taskServerTCP(void* ptParam) {
  server.begin(TCPProt);
  uint8_t i;
  while (1) {
    if (server.hasClient()) {  //判断是否有新的client请求进来
      for (i = 0; i < MAX_TCP_CLIENTS; i++) {
        //释放旧无效或者断开的client
        if (!serverClients[i] || !serverClients[i].connected()) {
          if (!serverClients[i]) {
            //serverClients[i]    判断指定序号的客户端是否有效
            serverClients[i].stop();  //停止指定客户端的连接
          }
          serverClients[i] = server.available();  //分配最新的client
          Serial.print("new TCP:");
          Serial.println(i);
          break;  //跳出一层for循环
        }
      }
      //当达到最大连接数 无法释放无效的client，需要拒绝连接
      if (i == MAX_TCP_CLIENTS) {
        WiFiClient client = server.available();
        client.stop();
        Serial.println("TCP MAX!");
      }
    }
    //检测client发过来的数据
    for (i = 0; i < MAX_TCP_CLIENTS; i++) {
      if (serverClients[i] && serverClients[i].connected()) {
        if (serverClients[i].available()) {
          String request = serverClients[i].readStringUntil('\n');
          if (!requestTest(request)) {
            continue;
          }
          requestString(request);
          if (transmit) {
            Serial.println(request);
            for (uint8_t j = 0; j < MAX_TCP_CLIENTS; j++) {
              if (i != j && serverClients[j] && serverClients[j].connected()) {
                serverClients[j].println(request);
              }
            }
            if (tcp_client.connected()) {
              tcp_client.println(request);
            }
          }
        }
      }
    }
  }
}
